# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '0OpTK6pBf5uUo4t2': {  # 亿联支付 支付宝H5 2.5% 1-3000 loki
        'API_KEY': 'dvIZAxcvmsqZ1IEHHvMPHTYR64SEXaFq',
        'gateway': 'https://www.91zkt.com/api/v1/data/order',
        'query_gateway': 'https://www.91zkt.com/api/v1/data/order',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    _LOGGER.info("yilianpay sign str: %s", s)
    return _gen_sign(s)


def generate_notify_sign(d, key):
    s = 'money={}&orderid={}&status={}&key={}'.format(d['money'], d['orderid'], d['status'], key)
    _LOGGER.info("yilianpay notify sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("yilianpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        return 'xd1006'
    return 'xd1006'


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    mch_id = info['app_id']
    service = info.get('service')
    key = _get_api_key(mch_id)
    parameter_dict = OrderedDict((
        ('orderid', str(pay.id)),
        ('type', _get_pay_type(service)),
        ('money', str(pay_amount)),
        ('attach', 'charge'),
        ('ip', _get_device_ip(info)),
        ('callbackurl', '{}/pay/api/{}/yilianpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('notifyurl', '{}/pay/api/{}/yilianpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, mch_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, key)
    _LOGGER.info("yilianpay create data: %s", json.dumps(dict(parameter_dict)))
    headers = {'Content-Type': 'application/x-www-form-urlencoded', 'token': '{}'.format(mch_id)}

    response = requests.post(_get_gateway(mch_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("yilianpay create rsp: %s, %s", response.text, response.url)
    j = json.loads(response.text)
    url = j['data']['pay_url'].replace('\/', '/')
    _LOGGER.info("yilianpay create url: %s, order_id is: %s", url, parameter_dict['orderid'])
    return {'charge_info': url}


def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("yilianpay notify data: %s", data)
    verify_notify_sign(data, key)
    pay_id = data['orderid']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('yilianpay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = data['orderid']
    total_fee = float(data['money'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '0000':
        _LOGGER.info('yilianpay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    key = _get_api_key(app_id)
    p_dict = {
        'out_trade_no': str(pay_id),
    }
    p_dict['sign'] = generate_sign(p_dict, key)
    _LOGGER.info(u'yilianpay query data: %s', json.dumps(p_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded', 'token': '{}'.format(app_id)}
    response = requests.get(_get_query_gateway(app_id), params=p_dict, headers=headers, timeout=3)
    _LOGGER.info(u'yilianpay query: %s', response.text)
    data = json.loads(response.text)['data']
    if response.status_code == 200:
        trade_status = int(data['status'])
        total_fee = float(data['money'])
        trade_no = data['out_trade_no']
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        # 0：未支付；1：支付成功
        if trade_status == 1:
            _LOGGER.info('yilianpay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('yilianpay data error, status_code: %s', response.status_code)
